import {reactive, watch} from 'vue'
import {defineStore} from 'pinia'
import {cacheKeys} from '@/stores/constant/cacheKey'
import {cloneDeep, isEmpty, isEqual} from 'lodash-es'
import {saveUserConfigApi} from '@/api/system/webConfig.api'
import {useUserStore} from '@/stores/modules/user.store'
import {messageSuccess} from '@/utils/commonUtil'
import {updateHtmlDarkClass} from '@/utils/darkUtil'

export const useWebConfigStore = defineStore(cacheKeys.WEB_CONFIG, () => {
			const layout = reactive<LayoutConfig>({
				/* 全局 */
				showDrawer: false,
				// 是否收缩布局(小屏设备)
				shrink: false,
				// 后台布局方式，可选值：'Default' | 'Classic' | 'Streamline'
				layoutMode: 'Default',
				// 页面切换动画，可选值：'slide-right' | 'slide-left' | 'el-fade-in-linear' | 'el-fade-in' | 'el-zoom-in-center' | 'el-zoom-in-top' | 'el-zoom-in-bottom'
				mainAnimation: 'slide-right',
				// 是否深色模式
				isDark: true,
				/* 侧边菜单 */
				// 侧边菜单背景色
				menuBackground: ['#ffffff', '#1d1e1f'],
				// 侧边菜单文字颜色
				menuColor: ['#303133', '#CFD3DC'],
				// 侧边菜单激活项背景色
				menuActiveBackground: ['#ffffff', '#1d1e1f'],
				// 侧边菜单激活项文字色
				menuActiveColor: ['#409eff', '#D57616'],
				// 侧边菜单顶栏背景色
				menuTopBarBackground: ['#fcfcfc', '#1d1e1f'],
				// 侧边菜单宽度(展开时)，单位px
				menuWidth: 260,
				// 侧边菜单项默认图标
				menuDefaultIcon: 'el-icon-Menu',
				// 是否水平折叠收起菜单
				menuCollapse: false,
				// 是否只保持一个子菜单的展开(手风琴)
				menuUniqueOpened: false,
				// 显示菜单栏顶栏(logo)
				menuShowTopBar: true,
				/* 顶栏 */
				// 顶栏背景色
				headerBarBackground: ['#ffffff', '#1d1e1f'],
				// 顶栏文字色
				headerBarTabColor: ['#000000', '#CFD3DC'],
				// 顶栏激活项背景色
				headerBarTabActiveBackground: ['rgba(64,158,255,0.1)', 'rgba(255,128,0,0.1)'],
				// 顶栏激活项文字色
				headerBarTabActiveColor: ['#409eff', '#ff8000'],
				// 顶栏悬停时背景色
				headerBarHoverBackground: ['rgba(64,158,255,0.5)', 'rgba(255,128,0,0.5)'],
				// 标签页是否显示图标
				tabIcon: true
			})

			const layoutDefault: LayoutConfig = {
				/* 全局 */
				showDrawer: false,
				// 是否收缩布局(小屏设备)
				shrink: false,
				// 后台布局方式，可选值：'Default' | 'Classic' | 'Streamline'
				layoutMode: 'Default',
				// 页面切换动画，可选值：'slide-right' | 'slide-left' | 'el-fade-in-linear' | 'el-fade-in' | 'el-zoom-in-center' | 'el-zoom-in-top' | 'el-zoom-in-bottom'
				mainAnimation: 'slide-right',
				// 是否深色模式
				isDark: true,
				/* 侧边菜单 */
				// 侧边菜单背景色
				menuBackground: ['#ffffff', '#1d1e1f'],
				// 侧边菜单文字颜色
				menuColor: ['#303133', '#CFD3DC'],
				// 侧边菜单激活项背景色
				menuActiveBackground: ['#ffffff', '#1d1e1f'],
				// 侧边菜单激活项文字色
				menuActiveColor: ['#409eff', '#D57616'],
				// 侧边菜单顶栏背景色
				menuTopBarBackground: ['#fcfcfc', '#1d1e1f'],
				// 侧边菜单宽度(展开时)，单位px
				menuWidth: 260,
				// 侧边菜单项默认图标
				menuDefaultIcon: 'el-icon-Menu',
				// 是否水平折叠收起菜单
				menuCollapse: false,
				// 是否只保持一个子菜单的展开(手风琴)
				menuUniqueOpened: false,
				// 显示菜单栏顶栏(logo)
				menuShowTopBar: true,
				/* 顶栏 */
				// 顶栏背景色
				headerBarBackground: ['#ffffff', '#1d1e1f'],
				// 顶栏文字色
				headerBarTabColor: ['#000000', '#CFD3DC'],
				// 顶栏激活项背景色
				headerBarTabActiveBackground: ['rgba(64,158,255,0.1)', 'rgba(255,128,0,0.1)'],
				// 顶栏激活项文字色
				headerBarTabActiveColor: ['#409eff', '#ff8000'],
				// 顶栏悬停时背景色
				headerBarHoverBackground: ['rgba(64,158,255,0.5)', 'rgba(255,128,0,0.5)'],
				// 标签页是否显示图标
				tabIcon: true
			}

			const lang = reactive<LangConfig>({
				// 默认语言，可选值<zh-cn|en>
				defaultLang: 'zh-cn',
				// 当在默认语言包找不到翻译时，继续在 fallbackLang 语言包内查找翻译
				fallbackLang: 'zh-cn',
				// 支持的语言列表
				langArray: [
					{value: 'zh-cn', name: '中文简体'},
					{value: 'en', name: 'English'}
				]
			})

			// 记录修改前的配置，以供对比
			let oldConfig: Partial<LayoutConfig & AnyObject> = {}

			watch(() => layout.showDrawer, value => {
				if (value) {
					saveOldConfigTemp()
				} else {
					saveConfig()
				}
			})

			const saveOldConfigTemp = () => {
				oldConfig = cloneDeep(layout)
			}

			const saveConfig = () => {
				// 比对配置是否有变化，如果有变化则找出变化的项，然后更新到数据库
				const newConfig: LayoutConfig & AnyObject = layout
				const changedConfig: SaveUserConfigRequest & AnyObject = {}
				for (const key in newConfig) {
					// 过滤掉不需要比对和持久化的项
					if (key === 'showDrawer' || key === 'shrink' || key === 'menuCollapse') {
						continue
					}
					if (!isEqual(newConfig[key], oldConfig[key])) {
						changedConfig[key] = newConfig[key]
					}
				}
				if (!isEmpty(changedConfig)) {
					changedConfig.userId = useUserStore().userId
					saveUserConfigApi(changedConfig).then(() => {
						messageSuccess('您的设置已保存')
					})
				}
			}

			// 监听深色模式的改变
			watch(() => layout.isDark, value => {
				updateHtmlDarkClass(value)
				onSetLayoutColorByMode()
			})

			// 监听布局方式的改变
			watch(() => layout.layoutMode, () => {
				onSetLayoutColorByMode()
			})

			const menuWidth = () => {
				if (layout.shrink) {
					return layout.menuCollapse ? '0px' : layout.menuWidth + 'px'
				}
				// 菜单是否折叠
				return layout.menuCollapse ? '64px' : layout.menuWidth + 'px'
			}

			// 切换布局时，如果是为默认配色方案，对菜单激活背景色重新赋值
			const onSetLayoutColorByMode = (layoutMode: LayoutConfig['layoutMode'] = layout.layoutMode) => {
				const tempValue = layout.isDark ? {idx: 1, color: '#1d1e1f', newColor: '#141414'} : {
					idx: 0,
					color: '#ffffff',
					newColor: '#f5f5f5'
				}
				if (layoutMode == 'Classic' && layout.headerBarBackground[tempValue.idx] === tempValue.color && layout.headerBarTabActiveBackground[tempValue.idx] === tempValue.color) {
					layout.headerBarTabActiveBackground[tempValue.idx] = tempValue.newColor
				} else if (layoutMode == 'Default' && layout.headerBarBackground[tempValue.idx] === tempValue.color && layout.headerBarTabActiveBackground[tempValue.idx] === tempValue.newColor) {
					layout.headerBarTabActiveBackground[tempValue.idx] = tempValue.color
				}
			}

			const setLayout = (name: keyof LayoutConfig, value: any) => {
				layout[name] = value as never
			}

			const getColorVal = (name: keyof Pick<LayoutConfig, 'menuBackground' | 'menuColor' | 'menuActiveBackground' | 'menuActiveColor' | 'menuTopBarBackground' | 'headerBarTabColor' | 'headerBarTabActiveBackground' | 'headerBarTabActiveColor' | 'headerBarBackground' | 'headerBarHoverBackground'>): string => {
				const colors = layout[name]
				if (layout.isDark) {
					return colors[1]
				} else {
					return colors[0]
				}
			}

			const resetLayout = (...skipProperties: (keyof LayoutConfig)[]) => {
				for (const key in layoutDefault) {
					if (skipProperties && skipProperties.length > 0 && skipProperties.includes(<keyof LayoutConfig>key)) {
						continue
					}
					(<LayoutConfig & AnyObject>layout)[key] = cloneDeep((<LayoutConfig & AnyObject>layoutDefault)[key])
				}
			}

			const resetLang = () => {
				lang.defaultLang = 'zh-cn'
				lang.fallbackLang = 'zh-cn'
				lang.langArray = [
					{value: 'zh-cn', name: '中文简体'},
					{value: 'en', name: 'English'}
				]
			}

			const resetWebConfigStore = () => {
				resetLayout()
				resetLang()
			}

			return {
				layout: layout,
				lang: lang,
				menuWidth: menuWidth,
				setLayout: setLayout,
				getColorVal: getColorVal,
				resetLayout: resetLayout,
				resetLang: resetLang,
				resetWebConfigStore: resetWebConfigStore
			}
		},
		{
			persist: {
				key: cacheKeys.WEB_CONFIG,
				storage: window.localStorage
			}
		}
)
